<?php
include("../common/session.php");
$seo = $crud->escape_string($_GET['seo']);
$result = $crud->getData("SELECT * FROM maincategory WHERE seo='$seo'");
foreach($result as $res){
	$id = $res['id'];
	$name = $res['name'];
	$metatitle = $res['metatitle'];
	$metakeyword = $res['metakeyword'];
    $metadescription = $res['metadescription'];
	$catid = $res['pid'];
}
$result2 = $crud->getData("SELECT * FROM category WHERE id='$catid'");
foreach($result2 as $res2){
	$catname = $res2['name'];
	$catseo = $res2['seo'];
}
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$currentURL = $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$canonicalURL = strtok($currentURL, '?');
?>
<!DOCTYPE html>
<html class="no-js" lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title><?php echo !empty($metatitle) ? $metatitle : $name; ?></title>
    <meta name="keywords" content="<?php echo $metakeyword; ?>">
    <meta name="description" content="<?php echo $metadescription; ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="canonical" href="<?php echo $canonicalURL; ?>" />
    <link rel="shortcut icon" href="../img/<?php echo $favlogo[0]['images'];?>" />
    <link rel="stylesheet" href="../assets/css/plugins.css">
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/style-min.css">
    <link rel="stylesheet" href="../assets/css/responsive.css">
		<style>
            .grid-products .item .product-image>a {
                border: solid 1px #ccc;
            }
            .sort-desc li {
                list-style-type: disc;
                margin-left: 20px;
            }
            .grid-products .list-style .sort-desc {
                height: 120px;
                overflow: hidden;
            }
            @media only screen and (min-width: 992px) {
                .button-set {
                    opacity: 1;
                    visibility: visible;
                    top: 10px;
                    right: 10px;
                }
            }
		</style>
		<script type="text/javascript">
		function addwishlist(idd){
			setTimeout(function () {
				$.ajax({
					url:"../common/addwishlist.php",
					data:$(".form"+idd).serialize(),
					type:"POST",
					success:function(res){
						var eee = res.split('@@@');
						$(".form"+idd).css("display","none");
						$(".ourproducts"+idd).html(eee[0]);
						$(".wishlist-count").html(eee[1]);
					}
				});
			},200);
		}
		function addwishlist2(idd){
			setTimeout(function () {
				$.ajax({
					url:"../common/removewishlist.php",
					data:$(".form2"+idd).serialize(),
					type:"POST",
					success:function(res){
						var eee = res.split('@@@');
						$(".form2"+idd).css("display","none");
						$(".ourproducts2"+idd).html(eee[0]);
						$(".wishlist-count").html(eee[1]);
					}
				});
			},200);
		}
		</script>
		<script>
            function getvalue(str){
            var XMLHttpRequestObject = false;
            if(window.XMLHttpRequest){
                XMLHttpRequestObject = new XMLHttpRequest();
            } else if(window.ActiveXObject){
                XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
            }
            XMLHttpRequestObject.open("GET", "datasearch.php?id=<?php echo $id;?>&dt="+str, true);
            XMLHttpRequestObject.send(null);
        
            XMLHttpRequestObject.onreadystatechange = function(){
                if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
                    document.getElementById('txt').innerHTML = XMLHttpRequestObject.responseText;
                    initPagination();
                }
            } 
        }
        
        function initPagination(){
            const itemsPerPage = 10;
            const productList = document.querySelectorAll("#txt .item");
            const totalItems = productList.length;
            const totalPages = Math.ceil(totalItems / itemsPerPage);
            const paginationDiv = document.getElementById("pagination");
        
            let currentPage = 1;
        
            function showPage(page) {
                productList.forEach((item, index) => item.style.display = "none");
        
                const start = (page - 1) * itemsPerPage;
                const end = start + itemsPerPage;
                for (let i = start; i < end && i < totalItems; i++) {
                    productList[i].style.display = "block";
                }
        
                renderPagination();
            }
        
            function renderPagination() {
                let buttons = "";
                if (currentPage > 1) {
                    buttons += `<button class="page-btn" onclick="goToPage(${currentPage - 1})">Prev</button>`;
                }
        
                if (currentPage > 2) {
                    buttons += `<button class="page-btn" onclick="goToPage(1)">1</button>`;
                    if (currentPage > 3) buttons += `<span class="dots">...</span>`;
                }
        
                let start = Math.max(1, currentPage - 1);
                let end = Math.min(totalPages, currentPage + 1);
        
                for (let i = start; i <= end; i++) {
                    if (i === currentPage) {
                        buttons += `<button class="page-btn active">${i}</button>`;
                    } else {
                        buttons += `<button class="page-btn" onclick="goToPage(${i})">${i}</button>`;
                    }
                }
        
                if (currentPage < totalPages - 1) {
                    if (currentPage < totalPages - 2) buttons += `<span class="dots">...</span>`;
                    buttons += `<button class="page-btn" onclick="goToPage(${totalPages})">${totalPages}</button>`;
                }
        
                if (currentPage < totalPages) {
                    buttons += `<button class="page-btn" onclick="goToPage(${currentPage + 1})">Next</button>`;
                }
        
                paginationDiv.innerHTML = buttons;
            }
        
            window.goToPage = function (page) {
                currentPage = page;
                showPage(page);
            };
        
            showPage(currentPage);
        }
        document.addEventListener("DOMContentLoaded", initPagination);
</script>
    </head>

    <body class="shop-page sidebar-filter shop-grid-view-page">
        <div class="page-wrapper">
            <?php 
			$pageurl = "../shop/$seo";
			include("../common/header.php");?>
			<style>
                .grid-products .item .product-image>a {
                        border: solid 1px #ccc;
                        border-radius: 15px;
                    }
            </style>
    
            <div id="page-content">
            <div class="page-header text-center">
                <div class="container">
                    <div class="row">
                        <div class="col-12 col-sm-12 col-md-12 col-lg-12 justify-content-between align-items-center">
                            <div class="page-title">
                                <h1><?php echo $name;?></h1>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="container" style="padding: 30px 0px;">
            
                <div class="row">
                    <!--Sidebar-->
                     <div class="toolbar toolbar-wrapper shop-toolbar">
                    <div class="row align-items-center">
                      
                        <div class="col-12 col-sm-10 col-md-10 col-lg-10 text-center product-count order-0 order-md-1 mb-3 mb-sm-0">
                            <div class="row">
                            <?php
                            if(empty($resultw)
                            ){null;} else{
                            ?>
                            <?php
                            $resultw = $crud->getData("SELECT * FROM maincategory WHERE pid='$id'");
                            foreach($resultw as $resw){
                            ?>
                            <div class="col-md-3 col-xs-6" id="huhhuh">
                                <a href="../shops/<?php echo $resw['seo'];?>" class="btn me-2 me-lg-3"><?php echo $resw['name'];;?></a>
                            </div>
                            <?php } }?>
                            </div>
                        </div>
                        <div
                            class="col-8 col-sm-6 col-md-2 col-lg-2 text-right filters-toolbar-item d-flex justify-content-end order-2 order-sm-2">
                            
                            <div class="filters-item d-flex align-items-center ms-2 ms-lg-3">
                                <label for="SortBy" class="mb-0 me-2 text-nowrap d-none">Sort by:</label>
                                <select name="SortBy" id="SortBy" class="filters-toolbar-sort" style="padding: 10px;width: 200px;"  onChange="getvalue(this.value);">
                                    <option value="featured" selected="selected">Featured</option>
                                    <option value="best-selling">Best selling</option>
                                    <option value="price-ascending">Price, low to high</option>
                                    <option value="price-descending">Price, high to low</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                    <!--End Sidebar-->

                    <!--Products-->
                    <div class="col-12 col-sm-12 col-md-12 col-lg-12 main-col">
                        <!--Product Grid-->
                        <div class="grid-products grid-view-items">
                            <div class="row col-row product-options row-cols-xl-5 row-cols-lg-4 row-cols-md-3 row-cols-sm-3 row-cols-2" id="txt">
                            <?php
                            $run1 = $crud->getData("SELECT * FROM products WHERE status=1 ORDER BY id ASC");
                            foreach($run1 as $row1){
                            $run2 = $crud->getData("SELECT * FROM product_image WHERE pid='$row1[id]' ORDER BY id ASC LIMIT 1");
                            foreach($run2 as $row2){
                                $productimagefront = $row2['image'];
                            }
                             $result11 = $crud->getData("SELECT * FROM warrent WHERE pid='$row1[id]'  ORDER BY id DESC LIMIT 1");
                            foreach($result11 as $res11){
                                $warrently = $res11['title'];
                            }
                            $run3 = $crud->getData("SELECT * FROM product_image WHERE pid='$row1[id]' ORDER BY id DESC LIMIT 1");
                            foreach($run3 as $row3){
                                $productimageback = $row3['image'];
                            }
                            $run4 = $crud->getData("SELECT * FROM wishlist WHERE productid='$row1[id]' and profileid='$profileid'");
                            foreach($run4 as $row4){
                                $heartproduct = $row4['productid'];
                            } 
                            $run5 = $crud->getData("SELECT sum(status) as status FROM  productreviews WHERE productid='$row1[id]'");
                            foreach($run5 as $row5){
                                $totalreview = $row5['status'];
                            }
                            $run6 = $crud->getData("SELECT AVG(rating) as average_rating FROM productreviews WHERE productid='$row1[id]'");
                                foreach($run6 as $row6){
                                    $averageRating = round($row6['average_rating'], 2); // Round to 1 decimal place
                            }
                            $cat_id = $id;
                            $cat = $row1['maincategory'];
                            $array = explode(",", $cat);
                            $j = count($array);
                            for($i=0;$i<$j;$i++){
                            if($cat_id == $array[$i]){ ?>
                                <div class="item col-item">
                                    <div class="product-box">
                                        <div class="product-image">
                                            <a href="../product/<?php echo $row1['seourl'];?>" class="product-img rounded-0">
                                                <img class="primary rounded-0 blur-up lazyload" data-src="../img/<?php echo $productimagefront;?>" src="../img/<?php echo $productimagefront;?>" alt="<?php echo $row1['name']; ?>" title="<?php echo $row1['name']; ?>" width="625" height="808" />
                                                <img class="hover rounded-0 blur-up lazyload" data-src="../img/<?php echo $productimageback;?>" src="../img/<?php echo $productimageback;?>" alt="<?php echo $row1['name']; ?>" title="<?php echo $row1['name']; ?>" width="625" height="808" />
                                            </a>
                                            <div class="product-labels"><span class="lbl on-sale" style="background: #fcc50b !important;color: black;"><i class="icon anm anm-star" style="margin-right: 6px;position: relative;top: -1px;"></i><?php if(empty($averageRating)){echo 5;}else{echo $averageRating;}?></span></div>
                                            <div class="d-flex" style="justify-content: space-between;background: black;padding: 3px 14px;color: white;border-radius: 0px 0px 15px 15px;">
                                    <span class="metafeild-label label--highlight custom-label label ui-2" style="font-size: 10px;text-transform: uppercase"><?php echo $warrently?></span>
                                    
                                </div>
                                        </div>
                                        <div class="product-details">
                                            <div class="product-name">
                                                <a href="../product/<?php echo $row1['seourl'];?>"><?php echo $row1['name']; ?>
                                                </a>
                                            </div>
                                            <div class="product-price">
                                                <span class="price">₹ <?php echo $row1['offerprice']; ?></span>
                                            </div>
                                            <ul class="variants-clr swatches">
                                                <?php
                                                $run10 = $crud->getData("SELECT * FROM product_image WHERE pid='$row1[id]'  LIMIT 4");
                                                foreach($run10 as $row10){
                                                ?>
                                                <li class="swatch medium radius"><span class="swatchLbl" data-bs-toggle="tooltip" data-bs-placement="top" title="<?php echo $row1['name'];?>"><img src="../img/<?php echo $row10['image'];?>" alt="<?php echo $row1['name']; ?>" width="625" height="808" /></span>
                                                </li>
                                                <?php } ?>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <?php } } } ?>
                            </div>
                        </div>
                    </div>
                    <div id="pagination" class="pagination mt-3 text-center" style="justify-content: center;"></div>
                </div>
            </div>
        </div>
        <style>
        #pagination .page-btn {
            margin: 2px;
            padding: 6px 12px;
            border: 1px solid #ddd;
            background: #fff;
            cursor: pointer;
            border-radius: 4px;
        }
        #pagination .page-btn.active {
            background: #1e1e1e;
            color: #fff;
        }
        
        #pagination .dots {
            margin: 0 5px;
            color: #666;
        }
        </style>
            <?php include("../common/footer.php");?>
        
        <script src="../assets/js/plugins.js"></script>
        <script src="../assets/js/main.js"></script>
    </body>
</html>
